﻿<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>信息录入</title>
	<meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="Edge" />
    <link href="https://cdn.bootcss.com/pickadate.js/3.5.6/compressed/themes/classic.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/pickadate.js/3.5.6/compressed/themes/classic.date.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/semantic-ui/2.2.10/semantic.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/datatables/1.10.15/css/dataTables.semanticui.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/dropzone/4.3.0/min/dropzone.min.css" rel="stylesheet">

    <style>
    </style>

    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/semantic-ui/2.2.10/semantic.min.js"></script>
    <script src="https://cdn.bootcss.com/datatables/1.10.15/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.bootcss.com/datatables/1.10.15/js/dataTables.semanticui.min.js"></script>
    <script src="https://cdn.bootcss.com/dropzone/4.3.0/min/dropzone.min.js"></script>
    <script src="https://cdn.bootcss.com/js-cookie/2.1.3/js.cookie.min.js"></script>
    <script src="https://cdn.bootcss.com/pickadate.js/3.5.6/compressed/picker.js"></script>
    <script src="https://cdn.bootcss.com/pickadate.js/3.5.6/compressed/picker.date.js"></script>
    <script src="https://cdn.bootcss.com/echarts/3.7.1/echarts.min.js"></script>
</head>
<body>

<div>
    <!--菜单栏-->
    <div class="ui top attached tabular blue inverted menu">
        <a class="item active" data-tab="record"><i class="calendar outline icon"></i>日志记录</a>
        <a class="item" data-tab="weekplan"><i class="file text outline icon"></i>每周计划</a>
        <a class="item" data-tab="todo"><i class="ordered list icon"></i>待办事项</a>
        <a class="item" data-tab="dailymod"><i class="star half empty icon"></i>每日心情</a>

        <div class="right menu">
            <div class="ui dropdown item">
                <img class="ui avatar image" src="/Images/DefUser.png"/>
                <div id="tb-user-name">语言</div>
                <i class="dropdown icon"></i>
                <div class="menu">
                    <a class="item disabled">个人主页</a>
                    <a id="btn-exit" class="item">退出</a>
                </div>
            </div>
        </div>

    </div>
    <!--日志记录分页-->
    <div class="ui bottom attached tab segment active" data-tab="record">
        <div>
            <div id="cb-imp-excel-delfirst" class="ui floated small toggle checkbox" data-inverted="" data-tooltip="选中时，导入Excel文件前，首先清空当前用户的已有记录。慎选！" data-position="bottom left">
                <label>首先删除原有数据</label>
                <input type="checkbox" name="public">
            </div>
            <div id="btn-out-excel" class="ui right floated small violet labeled icon button" data-inverted="" data-tooltip="将日志记录导出至Excel文件" data-position="bottom right">
                <i class="write square icon"></i> 导出Excel
            </div>
            <div id="btn-imp-excel" class="ui right floated small orange labeled icon button" data-inverted="" data-tooltip="导入Excel文件，Excel依次为：日期、工作描述、项目、活动类型、工作量、加班、请假、备注。其中备注为工作内容的详细解释" data-position="bottom right">
                <i class="table icon"></i> 导入Excel
            </div>
            <div id="btn-out-docx" class="ui right floated small orange labeled icon button" data-inverted="" data-tooltip="日志生成Word文件，文件以周为页进行分类" data-position="bottom left">
                <i class="table icon"></i> 生成Word
            </div>

        </div>
        <div class="ui hidden divider"></div>
        <div id="div-record-table">
            <table id="record-table" class="ui celled table" cellspacing="0" width="100%">
                <thead>
                <tr>
                    <th class="center aligned">ID</th>
                    <th class="center aligned">记录时间</th>
                    <th class="center aligned">工作描述</th>
                    <th class="center aligned">项目</th>
                    <th class="center aligned">活动类型</th>
                    <th class="center aligned">工作量</th>
                    <th class="center aligned">加班量</th>
                    <th class="center aligned">备注</th>
                </tr>
                </thead>
                <tfoot>
                <tr>
                    <th colspan="8">
                        <div id="btn-add-row" class="ui right floated small primary labeled icon button"><i class="plus icon"></i> 添加
                        </div>
                        <div id="btn-update-row" class="ui floated small icon button"><i class="write icon"></i> 修改
                        </div>
                        <div id="btn-del-row" class="ui floated small icon button"><i class="minus icon"></i> 删除
                        </div>
                    </th>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>
    <!--每周计划分页-->
    <div class="ui bottom attached tab segment" data-tab="weekplan">
        <div id="week-plan-root">

        </div>
    </div>
    <!--待办事项分页-->
    <div class="ui bottom attached tab segment" data-tab="todo">
        <!--添加事项面板-->
        <div class="ui form">
            <div class="fields">
                <div class="two wide field">
                    <div id="cb-todo-show-finished" class="ui floated toggle checkbox">
                        <label>显示完成项</label>
                        <input type="checkbox">
                    </div>
                </div>
                <div class="nine wide field">
                    <div class="ui input">
                        <input id="tb-todo-msg" type="text" placeholder="待办项...">
                    </div>
                </div>
                <div class="three wide field">
                    <input id="date-todo-finish" class="datepicker" placeholder="结束日期..."/>
                </div>
                <div class="two wide field">
                    <div id="btn-add-todo" class="ui right floated labeled button" tabindex="0">
                        <div class="ui basic blue button">
                            <i class="plus icon"></i> 添加
                        </div>
                        <a id="lbl-todo-num" class="ui basic left pointing blue label"> 0 </a>
                    </div>
                </div>
            </div>
        </div>
        <!--分隔行-->
        <div class="ui hidden divider"></div>
        <!--待办事项表格-->
        <table id="todo-table" class="ui single line padded table">
            <thead>
            <tr>
                <th class="zero wide">ID</th>
                <th class="one wide">完成</th>
                <th class="eleven wide">事项</th>
                <th class="two wide">结束时间</th>
                <th class="one wide">修改</th>
                <th class="one wide">删除</th>
            </tr>
            </thead>
            <tbody id="tbody-todo-table">
            <!--应该有的样子
            <tr>
                <td class="todo-id">1</td>
                <td class="collapsing">
                    <div class="ui fitted toggle checkbox">
                        <input type="checkbox"> <label></label>
                    </div>
                </td>
                <td class="todo-msg">浇花</td>
                <td class="todo-finish-time">September 14, 2013</td>
                <td>
                    <button class="ui basic button btn-todo-modify"><i class="icon user"></i> 修改 </button>
                </td>
                <td>
                    <button class="ui basic button btn-todo-del"><i class="icon user"></i> 删除 </button>
                </td>
            </tr>
            -->
            </tbody>
        </table>
    </div>
    <!--每日心情分页-->
    <div class="ui bottom attached tab segment" data-tab="dailymod">
        <div id="daily-mod-root">

            <div class="ui grid form">
                <div class="ui center aligned two wide column">
                    <div class="ui small header" style="margin-top: 8px;">起始时间</div>
                </div>
                <div class="four wide column">
                    <div class="large field">
                        <input id="date-mod-start" class="datepicker"/>
                    </div>
                </div>
                <div class="ui center aligned two wide column">
                    <div class="ui small header" style="margin-top: 8px;">结束时间</div>
                </div>
                <div class="four wide column">
                    <div class="field">
                        <input id="date-mod-end" class="datepicker"/>
                    </div>
                </div>
                <div class="two wide column">
                </div>
                <div class="two wide column">
                    <div id="btn-mod-create" class="ui small labeled blue icon button" data-inverted="" data-tooltip="刷新心情图表" data-position="bottom right">
                        <i class="line chart icon"></i> 刷新图表
                    </div>
                </div>
            </div>
            <div class="ui hidden divider"></div>
            <!--心情图表-->
            <div id="chart-mod"></div>

        </div>
    </div>
</div>

<div name="models">
    <!--等待模态框-->
    <div id="modal-loading" class="ui modal">
        <div class="ui icon message">
            <i class="notched circle loading icon"></i>
            <div class="content">
                <div class="header">请稍等</div>
                <p>读取中...</p>
            </div>
        </div>
    </div>
    <!--提示模态框-->
    <div id="modal-alert" class="ui small modal">
        <div id="div-alert-header" class="header" visibility="hidden">标题</div>
        <div class="content">
            <div id="div-alert-text" visibility="true">正文</div>
        </div>
        <div class="actions">
            <div class="ui right positive button">确定</div>
        </div>
    </div>
    <!--导出Excel信息录入模态框-->
    <div id="modal-download-date" class="ui modal">
        <div class="header">
            选择日期范围
        </div>
        <div style="margin: 20px" class="ui form">
            <div class="two fields">
                <div class="field">
                    <label>起始日期</label>
                    <input id="date-download-start" class="datepicker"/>
                </div>
                <div class="field">
                    <label>结束日期</label>
                    <input id="date-download-end" class="datepicker"/>
                </div>
            </div>
        </div>
        <div class="actions">
            <div id="btn-export-excel-cancel" class="ui black deny button">取消</div>
            <div id="btn-export-excel-ok" class="ui positive right labeled icon button">确定<i class="checkmark icon"></i>
            </div>
        </div>
    </div>
    <!--导出Word日志信息录入模态框-->
    <div id="modal-docx-date" class="ui modal">
        <div class="header">
            选择日期范围
        </div>
        <div style="margin: 20px" class="ui form">
            <div class="two fields">
                <div class="field">
                    <label>起始日期</label>
                    <input id="date-docx-start" class="datepicker" />
                </div>
                <div class="field">
                    <label>结束日期</label>
                    <input id="date-docx-end" class="datepicker" />
                </div>
            </div>
        </div>
        <div class="actions">
            <div id="btn-export-docx-cancel" class="ui black deny button">取消</div>
            <div id="btn-export-docx-ok" class="ui positive right labeled icon button" autofocus="autofocus">
                确定<i class="checkmark icon"></i>
            </div>
        </div>
    </div>
    <!--日志行数据信息模态框-->
    <div id="modal-row" class="ui modal">
        <div class="header">
            日志数据
        </div>
        <div style="margin: 20px" class="ui form">
            <div class="field">
                <label>工作描述</label>
                <input id="input-row-rec-text" type="text">
            </div>
            <div class="two fields">
                <div class="field">
                    <label>项目名称</label>
                    <select id="select-project-name" class="ui search dropdown">
                        <option value="">选择项目名称</option>
                        <option value="AF">Afghanistan</option>
                        <option value="AX">Åland Islands</option>
                    </select>
                </div>
                <div class="field">
                    <label>活动类型</label>
                    <select id="select-project-type" class="ui search dropdown">
                        <option value="">选择活动类型</option>
                        <option value="AF">Afghanistan</option>
                        <option value="AX">Åland Islands</option>
                    </select>
                </div>
            </div>
            <div class="fields">
                <div class="four wide field">
                    <label>工作量(h)</label>
                    <input id="input-row-rec-workhour" type="text" name="card[number]" maxlength="16" placeholder="0"/>
                </div>
                <div class="four wide field">
                    <label>加班量(h)</label>
                    <input id="input-row-rec-overwork" type="text" name="card[cvc]" maxlength="3" placeholder="0"/>
                </div>
                <div class="four wide field">
                    <label>日期</label>
                    <input id="date-row-rec-date" class="datepicker"/>
                </div>
            </div>
            <div>
                <div class="field">
                    <label>备注</label>
                    <textarea id="input-row-rec-remark" rows="3"></textarea>
                </div>
            </div>
        </div>
        <div class="actions">
            <div class="ui black deny button">取消</div>
            <div id="btn-modal-row-ok" class="ui positive right labeled icon button">
                确定<i class="checkmark icon"></i>
            </div>
        </div>
    </div>
    <!--修改待办事项行信息模态框-->
    <div id="modal-todo-row" class="ui modal">
        <div class="header">
            修改待办事项信息
        </div>
        <div style="margin: 20px" class="ui form">
            <div class="three fields">
                <div class="field">
                    <label>完成</label>
                    <div id="cb-todo-row-modify" class="ui fitted toggle checkbox">
                        <input type="checkbox"> <label></label>
                    </div>
                </div>
                <div class="field">
                    <label>待办事项</label>
                    <input id="tb-todo-row-modify" type="text" placeholder="待办项...">
                </div>
                <div class="field">
                    <label>完成日期</label>
                    <input id="date-todo-row-modify" class="datepicker"/>
                </div>
            </div>
        </div>
        <div class="actions">
            <div class="ui black deny button">取消</div>
            <div id="btn-todo-row-modify-ok" class="ui positive right labeled icon button">
                确定<i class="checkmark icon"></i>
            </div>
        </div>
    </div>
</div>


<script>

    var _debug = true;
    var table;
    var rows;
    var userName;
    var storage;

    var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
    var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

    // 为string添加功能
    function stringExtFunction() {
        // 为字符串加入trim方法
        String.prototype.trim = function () { return this.replace(/(^\s+)|(\s+$)/g, '') }
        // stratsWith
        if (typeof String.prototype.startsWith != 'function') {
            String.prototype.startsWith = function (prefix) {
                return this.slice(0, prefix.length) === prefix;
            };
        }
        // endsWith
        if (typeof String.prototype.endsWith != 'function') {
            String.prototype.endsWith = function (suffix) {
                return this.indexOf(suffix, this.length - suffix.length) !== -1;
            };
        }
    }

    // 下载文件
    function downloadFile(url) {
        //iOS devices do not support downloading. We have to inform user about this.
        if (/(iP)/g.test(navigator.userAgent)) {
            alert('您的浏览器不支持下载功能，请使用桌面版浏览器！');
            return false;
        }

        //If in Chrome or Safari - download via virtual link click
        if (isChrome || isSafari) {
            //Creating new link node.
            var link = document.createElement('a');
            link.href = url;
            if (link.download !== undefined) {
                //Set HTML5 download attribute. This will prevent file from opening if supported.
                var fileName = url.substring(url.lastIndexOf('/') + 1, url.length);
                link.download = fileName;
            }

            //Dispatching click event.
            if (document.createEvent) {
                var e = document.createEvent('MouseEvents');
                e.initEvent('click', true, true);
                link.dispatchEvent(e);
                return true;
            }
        }

        // Force file download (whether supported by server).
        if (url.indexOf('?') === -1) {
            url += '?download';
        }

        window.open(url, '_self');
        return true;
    }

    // 显示alert框
    function showAlert(text, header) {
        var $alertHeader = $('#div-alert-header');
        var $alertText = $('#div-alert-text');

        if (header == null || header == '') {
            $alertHeader.attr('visibility', 'hidden');
            $alertHeader.text('');
        } else {
            $alertHeader.attr('visibility', 'visible');
            $alertHeader.text(header);
        }
        $alertText.text(text);

        $('#modal-alert').modal('show');
    }

    // 初始化图片上传区
    function intiDropzone() {
        var myDropzone = new window.Dropzone("#btn-imp-excel", {
            url: "FileHandler.aspx",
            maxFilesize: 5,
            acceptedFiles: ".xls,.xlsx"
        });
        myDropzone.on("complete", function (file) {
            var filerealname = Cookies.get(file.name);      //从cookies读取上传后的真实文件名（考虑到上传前的重名情况）
            if (filerealname == null || filerealname === "")
                filerealname = file.name;

            if (_debug) console.log(filerealname);

            var delFirst = $('#cb-imp-excel-delfirst').checkbox('is checked');
            $.ajax({
                type: "POST",
                url: "/Pages/DbService.asmx/ImportExcel",
                data: "{'userName':'" + userName + "','fileName':'" + filerealname + "','deleteFirst':'" + delFirst + "'}",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d != null) {
                        if (response.d === "Success") {
                            location.reload();
                            if (_debug) console.log('上传文件' + filerealname + '成功');
                        } else {
                            if (_debug) console.log('上传文件' + filerealname + '失败');
                        }
                    }
                },
                error: function (err) {
                    console.log('上传文件' + filerealname + '失败');
                }
            });

            myDropzone.removeFile(file);
        });
    }

    // 得到项目名称列表
    function getProjectNames() {
        var res = null;
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/Pages/DbService.asmx/GetProjectNames",
            dataType: 'json',
            async: false,
            timeout: 3000,
            error: function(x, e) {
                if (_debug) console.log(e);
            },
            success: function(result) {
                res = eval('(' + result.d + ')');
            }
        });

        return res;
    }
    
    // 得到活动类型列表
    function getProjectTypes() {
        var res = null;
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/Pages/DbService.asmx/GetProjectTypes",
            dataType: 'json',
            async: false,
            timeout: 3000,
            error: function (x, e) {
                if (_debug) console.log(e);
            },
            success: function (result) {
                res = eval('(' + result.d + ')');
            }
        });

        return res;
    }

    // 清空日志表
    function ClearRecordTable() {
        $('#record-table tbody').unbind('click');
        $('#div-record-table').text("");
        $('#div-record-table').append(
            '<table id="record-table" class="ui celled table" cellspacing="0" width="100%">' +
            '<thead>' +
            '<tr>' +
            '<th class="center aligned">ID</th>' +
            '<th class="center aligned">记录时间</th>' +
            '<th class="center aligned">工作描述</th>' +
            '<th class="center aligned">项目</th>' +
            '<th class="center aligned">活动类型</th>' +
            '<th class="center aligned">工作量</th>' +
            '<th class="center aligned">加班量</th>' +
            '<th class="center aligned">备注</th>' +
            '</tr>' +
            '</thead>' +
            '<tfoot>' +
            '<tr>' +
            '<th colspan="8">' +
            '<div id="btn-add-row" class="ui right floated small primary labeled icon button"><i class="plus icon"></i> 添加 </div>' +
            '<div id="btn-update-row" class="ui floated small icon button"><i class="write icon"></i> 修改 </div>' +
            '<div id="btn-del-row" class="ui floated small icon button"><i class="minus icon"></i> 删除 </div>' +
            '</th>' +
            '</tr>' +
            '</tfoot>' +
            '</table>'
        );
    }

    // 刷新日志表
    function FreshRecordTable() {
        var $dimmer = $('.dimmer');
        $('#modal-loading').modal('show');
        // 清除原有数据
        ClearRecordTable();
        // 刷新数据
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/Pages/DbService.asmx/GetAllRecords",
            data: "{userName:'" + userName + "'}",
            dataType: 'json',
            timeout: 3000,
            error: function (x, e) {
                showAlert('日志数据读取失败！');
                if (_debug) console.log(e);
            },
            complete: function (request, status) {
                // 延缓关闭读取等待框，避免读取速度过快无法关闭
                var timerTmp = window.setTimeout(function () {
                    $('#modal-loading').modal('hide');
                    if (timerTmp != null) window.clearTimeout(timerTmp);
                }, 1000);
            },
            success: function (result) {
                var json = eval('(' + result.d + ')');
                if (_debug) {
                    console.log('FreshRecordTable 结果：');
                    console.log(json);
                }
                rows = json;

                table = $('#record-table').DataTable({
                    data: json,
                    stateSave: true,
                    columns: [
                        { data: "ID" },
                        { data: "记录时间" },
                        { data: "工作描述" },
                        { data: "项目" },
                        { data: "活动类型" },
                        { data: "工作量" },
                        { data: "加班量" },
                        { data: "备注" }
                    ],
                    language: {
                        "lengthMenu": "每页显示 _MENU_ 行",
                        "zeroRecords": "没有匹配结果",
                        "info": "显示第 _PAGE_ 页， 共 _PAGES_ 页",
                        "infoEmpty": "没有记录",
                        "infoFiltered": "(从 _MAX_ 条记录中查询得到)",
                        "thousands": ",",
                        "loadingRecords": "加载中...",
                        "processing": "处理中...",
                        "search": "查找:",
                        "paginate": {
                            "first": "首页",
                            "last": "末页",
                            "next": "下一页",
                            "previous": "上一页"
                        }
                    }
                });
                // 隐藏ID列（暂不隐藏）
                // var column = table.column(0);
                // column.visible(!column.visible());

                $('#record-table tbody').unbind('click');
                $('#record-table tbody').on('click', 'tr', function () {
                    if (_debug) {
                        console.log('选中行的数据为：');
                        console.log(table.row(this).data());
                    }

                    if ($(this).hasClass('selected warning')) {
                        $(this).removeClass('selected warning');
                    }
                    else {
                        table.$('tr.selected').removeClass('selected warning');
                        $(this).addClass('selected warning');
                    }
                });
            }
        });
        // 绑定更新按钮
        $('#btn-update-row').unbind('click');
        $('#btn-update-row').click(function () {
            // 得到选中行的信息
            if (table == null) table = $('#record-table').DataTable();
            var selectedData = table.rows('.selected').data()[0];
            if (selectedData == null) {
                showAlert('未选择行！');
                return;
            }
            // 获取下拉列表数据
            var projectNames = getProjectNames();
            var projectTypes = getProjectTypes();
            // 更新下拉列表数据
            var $selectProjectName = $('#select-project-name');
            $selectProjectName.html("");
            $.each(projectNames, function (index, item) {
                $selectProjectName.append('<option value="' + item + '">' + item + '</option>');
            });

            var $selectProjectType = $('#select-project-type');
            $selectProjectType.html("");
            $.each(projectTypes, function (index, item) {
                $selectProjectType.append('<option value="' + item + '">' + item + '</option>');
            });
            // 写入下拉列表显示数据
            $selectProjectName.dropdown('set text', selectedData['项目']);
            $selectProjectType.dropdown('set text', selectedData['活动类型']);
            // 修改表单项为待修改列的值
            $('#input-row-rec-text').val(selectedData['工作描述']);
            $('#input-row-rec-workhour').val(selectedData["工作量"]);
            $('#input-row-rec-overwork').val(selectedData['加班量']);
            $('#input-row-rec-remark').val(selectedData['备注']);
            var dateRecs = selectedData['记录时间'].split("-");
            var dateR = new Date(dateRecs[0], dateRecs[1] - 1, dateRecs[2]);
            var $dateRec = $('#date-row-rec-date').pickadate('picker');
            $dateRec.set('select', dateR);
            $dateRec.set('view', dateR);
            // 更新确认按钮的点击功能
            $('#btn-modal-row-ok').unbind('click');
            $('#btn-modal-row-ok').click(function () {
                // 上传数据行
                var json = new Object();
                json.id = selectedData['ID'];
                json.recDate = $dateRec.get('highlight', 'yyyy-mm-dd');
                json.text = $('#input-row-rec-text').val();
                json.projectName = $selectProjectName.dropdown('get text')[0],
                    json.typeName = $selectProjectType.dropdown('get text')[0],
                    json.workHour = $('#input-row-rec-workhour').val();
                json.overtime = $('#input-row-rec-overwork').val();
                json.remark = $('#input-row-rec-remark').val();

                $('#modal-loading').modal('show');

                $.ajax({
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    url: "/Pages/DbService.asmx/UpdateRecord",
                    data: "{json:'" + JSON.stringify(json) + "'}",
                    dataType: 'json',
                    timeout: 10000,
                    complete: function (request, status) {
                        // 延缓关闭读取等待框，避免读取速度过快无法关闭
                        var timerTmp = window.setTimeout(function () {
                            $('#modal-loading').modal('hide');
                            if (timerTmp != null) window.clearTimeout(timerTmp);
                        }, 1000);
                    },
                    error: function (x, e) {
                        if (_debug) console.log(e);
                    },
                    success: function (result) {
                        if (result.d !== "Success") {
                            if (_debug) console.log('更新日志行数据失败！');
                            return;
                        }
                        // 修改前台页面的显示
                        FreshRecordTable();
                    }
                });
            });
            // 显示模态框
            $('#modal-row').modal('show');
        });
        // 绑定删除按钮
        $('#btn-del-row').unbind('click');
        $('#btn-del-row').click(function () {
            // 得到选中行的信息
            if (table == null) table = $('#record-table').DataTable();
            var selectedData = table.rows('.selected').data()[0];
            if (selectedData == null) {
                showAlert('未选择行！');
                return;
            }
            $('#modal-loading').modal('show');
            var delId = selectedData['ID'];

            $.ajax({
                type: "POST",
                contentType: "application/json;charset=utf-8",
                url: "/Pages/DbService.asmx/DeleteRecord",
                data: "{id:'" + delId + "'}",
                dataType: 'json',
                timeout: 3000,
                complete: function (request, status) {
                    // 延缓关闭读取等待框，避免读取速度过快无法关闭
                    var timerTmp = window.setTimeout(function () {
                        $('#modal-loading').modal('hide');
                        if (timerTmp != null) window.clearTimeout(timerTmp);
                    }, 1000);
                },
                error: function (x, e) {
                    if (_debug) console.log(e);
                },
                success: function (result) {

                    if (result.d !== "Success") {
                        if (_debug) console.log('删除日志行数据失败！');
                        return;
                    }
                    // 修改前台页面的显示
                    table.row('.selected').remove().draw(false);
                }
            });
        });
        // 绑定添加按钮
        $('#btn-add-row').unbind('click');
        $('#btn-add-row').on('click', function () {
            // 获取下拉列表数据
            var projectNames = getProjectNames();
            var projectTypes = getProjectTypes();
            // 更新下拉列表数据
            var $selectProjectName = $('#select-project-name');
            $selectProjectName.html("");
            $.each(projectNames, function (index, item) {
                $selectProjectName.append('<option value="' + item + '">' + item + '</option>');
            });

            var $selectProjectType = $('#select-project-type');
            $selectProjectType.html("");
            $.each(projectTypes, function (index, item) {
                $selectProjectType.append('<option value="' + item + '">' + item + '</option>');
            });
            // 写入下拉列表显示数据（选择第一项）
            $('.dropdown').dropdown('set selected', 0);
            // 修改表单项为默认值
            $('#input-row-rec-text').val('');
            $('#input-row-rec-workhour').val('0');
            $('#input-row-rec-overwork').val('0');
            $('#input-row-rec-remark').val('');
            var $dateRec = $('#date-row-rec-date').pickadate('picker');
            $dateRec.set('select', new Date());
            $dateRec.set('view', new Date());
            // 更新确认按钮的点击功能
            $('#btn-modal-row-ok').unbind('click');
            $('#btn-modal-row-ok').click(function () {
                // 上传数据行
                var json = new Object();
                json.userName = userName;
                json.recDate = $dateRec.get('highlight', 'yyyy-mm-dd');
                json.text = $('#input-row-rec-text').val();
                json.projectName = $selectProjectName.dropdown('get text')[0];
                json.typeName = $selectProjectType.dropdown('get text')[0];
                json.workHour = $('#input-row-rec-workhour').val();
                json.overtime = $('#input-row-rec-overwork').val();
                json.remark = $('#input-row-rec-remark').val();

                $('#modal-loading').modal('show');

                $.ajax({
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    url: "/Pages/DbService.asmx/AddRecord",
                    data: "{json:'" + JSON.stringify(json) + "'}",
                    dataType: 'json',
                    timeout: 10000,
                    complete: function (request, status) {
                        // 延缓关闭读取等待框，避免读取速度过快无法关闭
                        var timerTmp = window.setTimeout(function () {
                            $('#modal-loading').modal('hide');
                            if (timerTmp != null) window.clearTimeout(timerTmp);
                        }, 1000);
                    },
                    error: function (x, e) {
                        if (_debug) console.log(e);
                    },
                    success: function (result) {
                        if (result.d !== "Success") {
                            if (_debug) console.log('添加日志行数据失败！');
                            return;
                        }
                        // 修改前台页面的显示
                        FreshRecordTable();
                        //table.row.add(rows[0]).draw(false);
                    }
                });
            });
            // 显示模态框
            $('#modal-row').modal('show');
        });
    }

    // 刷新心情数据
    function freshModDate() {
        // 获取起止日期
        var $dateModStart = $('#date-mod-start').pickadate('picker');
        var $dateModEnd = $('#date-mod-end').pickadate('picker');
        var startDateMod = $dateModStart.get('highlight', 'yyyy-mm-dd');
        var endDateMod = $dateModEnd.get('highlight', 'yyyy-mm-dd');
        // 制作数组
        var dateList = [], dateDic = [];
        var strsStart = startDateMod.split("-");
        var startTime = new Date(strsStart[0], '0', '1');
        var strsEnd = endDateMod.split("-");
        var endTime = new Date(strsEnd[0], '11', '31'); // echarts日期图数据必须为整年

        while ((endTime.getTime() - startTime.getTime()) >= 0) {
            var year = startTime.getFullYear();
            var month =  (startTime.getMonth() + 1).toString();
            if (startTime.getMonth().toString().length == 1) month = '0' + month;
            var day = startTime.getDate().toString();
            if (startTime.getDate().toString().length == 1) day = '0' + day;
            dateDic[year + "-" + month + "-" + day] = 1;

            startTime.setDate(startTime.getDate() + 1);
        }

        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/Pages/DbService.asmx/GetDailyMods",
            data: "{userName:'" + userName + "',startDate:'" + startDateMod + "',endDate:'" + endDateMod + "'}",
            dataType: 'json',
            timeout: 10000,
            error: function (x, e) {
                if (_debug) console.log(e);
                return null;
            },
            success: function (result) {
                if (result.d === "") {
                    if (_debug) console.log('获取心情数据失败！');
                    return null;
                }
                // 转码得到的数据
                var res = eval('(' + result.d + ')');
                for (var prop in res) {
                    dateDic[prop] = res[prop];
                }
                for (var prop in dateDic) {
                    dateList.push([prop, dateDic[prop]]);
                }
                // 更新图表控件区域大小
                var countMonth = strsEnd[1] - strsStart[1] + 1;
                $('#chart-mod').width(document.body.clientWidth - 30);
                $('#chart-mod').height(300 * countMonth);
                // 初始化Mod图表
                var myChartMod = echarts.init(document.getElementById('chart-mod'));
                var optChartMod = {
                    tooltip: {
                        formatter: function (params) {
                            return '心情指数: ' + (params.value[1] * 100).toFixed(0) + '%';
                        }
                    },
                    visualMap: {
                        show: false,
                        min: 0,
                        max: 1.01,
                        calculable: true,
                        seriesIndex: [1],
                        orient: 'horizontal',
                        left: 'center',
                        bottom: 20,
                        inRange: {
                            color: ['#e0ffff', '#006edd'],
                            opacity: 0.6
                        },
                        controller: {
                            inRange: {
                                opacity: 0.5
                            }
                        }
                    },
                    calendar: [
                        {
                            left: 'center',
                            top: 'middle',
                            cellSize: 'auto',
                            yearLabel: { show: false },
                            orient: 'vertical',
                            dayLabel: {
                                firstDay: 1,
                                nameMap: 'cn'
                            },
                            monthLabel: { show: false },
                            range: [startDateMod, endDateMod]
                        }
                    ],
                    series: [
                        {
                            type: 'scatter',
                            coordinateSystem: 'calendar',
                            symbolSize: 1,
                            label: {
                                normal: {
                                    show: true,
                                    formatter: function (params) {
                                        var d = echarts.number.parseDate(params.value[0]);
                                        return d.getDate();
                                    },
                                    offset: [-40, -30],
                                    textStyle: {
                                        fontSize: 20,
                                        color: '#000'
                                    }
                                }
                            },
                            data: dateList
                        },
                        {
                            name: '心情',
                            type: 'heatmap',
                            coordinateSystem: 'calendar',
                            data: dateList
                        }
                    ]
                };
                myChartMod.setOption(optChartMod);
                //绘制表情图
                function getGraphSeries(chartData, chart) {
                    var startdate = +echarts.number.parseDate(startDateMod);
                    var enddate = +echarts.number.parseDate(endDateMod);

                    return echarts.util.map(chartData, function (item, index) {
                        var date = +echarts.number.parseDate(item[0]);
                        if (date < startdate || date > enddate) return "{}";

                        var centerPos = chart.convertToPixel('calendar', item);
                        if (isNaN(centerPos[0])) return "{}";

                        var graphData = [[date, item[1] ]];
                        var imgPath;
                        if (item[1] > 0.6) imgPath = 'image://../Images/smile.svg';
                        else if (item[1] > 0.4) imgPath = 'image://../Images/meh.svg';
                        else imgPath = 'image://../Images/frown.svg';

                        return {
                            type: 'graph',
                            coordinateSystem: 'calendar',
                            symbol: imgPath,
                            symbolSize: [45, 45],
                            calendarIndex: 0,
                            data: graphData,
                            z: 20,
                            itemStyle: {
                                normal: {
                                    color: 'red',
                                    opacity: 0.5
                                }
                            }
                        };
                    });
                }
                //延时以获取日历表格坐标
                setTimeout(function () {
                    //绘制表情图
                    myChartMod.setOption({
                        series: getGraphSeries(dateList, myChartMod)
                    });
                    //重绘被覆盖掉的series
                    myChartMod.setOption({
                        series: [
                            {
                                type: 'scatter',
                                coordinateSystem: 'calendar',
                                symbolSize: 1,
                                label: {
                                    normal: {
                                        show: true,
                                        formatter: function (params) {
                                            var d = echarts.number.parseDate(params.value[0]);
                                            return d.getDate();
                                        },
                                        offset: [-40, -30],
                                        textStyle: {
                                            fontSize: 20,
                                            color: '#000'
                                        }
                                    }
                                },
                                data: dateList,
                            },
                            {
                                name: '心情',
                                type: 'heatmap',
                                coordinateSystem: 'calendar',
                                data: dateList,
                            }
                        ]
                    });
                }, 30);

            }
        });
    }

    // 得到单周计划的html字符串
    function getStrHtmlWeekPlanList(date, listText) {
        var hadBlank = false;
        // 加入起始
        var htmlText = '<div class="ui segment">';
        htmlText += '<h4 class="ui header">' + date + '</h4>';
        htmlText += '<div class="ui stacked segments">';
        // 添加列表项
        var plans = listText.split(',');
        plans.forEach(function (value, index, array) {
            if (value != null && value !== '') {
                htmlText += '<div class="ui segment week-plan-line" mod-status="1" onclick="onWeekPlanItemClicked.call(this)"><p>';
                htmlText += value;
                htmlText += '</p></div>';
            } else {
                hadBlank = true;
            }
        });
        // 列表尾部加入可添加空白项
        if (listText === '') hadBlank = false;
        if (hadBlank === false) {
            htmlText += '<div class="ui segment week-plan-line" mod-status="1" onclick="onWeekPlanItemClicked.call(this)"><p></p></div></div></div>';

            return htmlText;
        }
        // 加入结尾并返回
        htmlText += '</div></div>';
        return htmlText;
    }

    // 响应周计划单项点击事件
    function onWeekPlanItemClicked() {
        // 得到列表日期
        var date = this.parentNode.parentNode.firstChild.innerText;
        console.log(this.parentNode.parentNode.firstChild);
        console.log(this.parentNode.parentNode.firstChild.nextSibling);
        console.log('date:' + date);
        // 得到当前的列表行文字
        var planText = this.innerText;
        if (planText == undefined || planText === '') {
            try {
                planText = this.firstChild.firstChild.value;
            } catch (e) {
                planText = '';
            }
        }
        if (planText == undefined) planText = '';
        // 切换列表行输入状态
        var modStatus = this.getAttribute("mod-status");
        var wasP = modStatus === "1";
        var ps = null, listPlan = null;

        if (wasP) {
            this.innerHTML = '<div class="ui input focus"><input type="text" value=""></div>';
            this.setAttribute("mod-status", "2");
            this.firstChild.firstChild.focus();
            this.firstChild.firstChild.setAttribute('value', planText);
        } else {
            this.innerHTML = '<p>' + planText + '</p>';
            this.setAttribute("mod-status", "1");
            // 上传
            ps = $(this.parentNode).find('p');              // 当前列表下的行集合
            listPlan = '';                                  // 当前列表下所有非空行合为一个字符串，以逗号间隔
            ps.each(function (index, item) {
                if (item.innerText != null && item.innerText !== '') {
                    listPlan += (item.innerText + ',');
                }
            });

            if (listPlan !== '') {
                listPlan = listPlan.substring(0, listPlan.length - 1);

                $.ajax({
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    url: "/Pages/DbService.asmx/UpdateWeekPlan",
                    data: "{userName:'" + userName + "',text:'" + listPlan + "',date:'" + date + "'}",
                    dataType: 'json',
                    async: false,
                    timeout: 3000,
                    complete: function (xhr, status) {
                        if (_debug) console.log('周计划上传结果：' + status);
                    }
                });
            }
        }
        // 遍历
        if (!wasP) {
            console.log(this.parentNode);

            var countEmptyLine = 0;           // 是否已包含空行
            ps.each(function (index, item) {
                console.log('---' + item.innerText + '---')
                if (item.innerText == null || item.innerText === '') {
                    countEmptyLine++;
                }
            });
            console.log('countEmptyLine:' + countEmptyLine);

            if (countEmptyLine === 0) {
                $(this.parentNode).append('<div class="ui segment week-plan-line" mod-status="1" onclick="onWeekPlanItemClicked.call(this)"><p></p></div></div></div>');
            }
            if (countEmptyLine > 1) {
                console.log('listPlan:' + listPlan);
                this.parentNode.parentNode.innerHTML = getStrHtmlWeekPlanList(date, listPlan);
            }
        }
    }

    // 初始化日期选择控件
    function intiDate() {
        var $datepickerinput = $('.datepicker').pickadate({
            format: 'yyyy-mm-dd',
            formatSubmit: 'yyyy-mm-dd',
            hiddenPrefix: 'prefix__',
            hiddenSuffix: '__suffix',
            //editable: true,
            min: new Date(2016, 1, 1),
            max: new Date(2020, 12, 31),
            showMonthsShort: true,
            labelMonthNext: '下一月',
            labelMonthPrev: '上一月',
            labelMonthSelect: '选择月份',
            labelYearSelect: '选择年份',
            monthsFull: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
            weekdaysShort: ['日', '一', '二', '三', '四', '五', '六'],
            today: '今天',
            clear: '清除'
        });
        // 初始化每日心情页面
        var defDateStartMod = new Date();
        defDateStartMod.setDate(defDateStartMod.getDate() - 30);
        var defDateEndMod = new Date();
        var $dateStartMod = $('#date-mod-start').pickadate('picker');
        $dateStartMod.set('select', defDateStartMod);
        var $dateEndMod = $('#date-mod-end').pickadate('picker');
        $dateEndMod.set('select', defDateEndMod);
        // 初始化Excel输出弹出窗体
        var defDateStart = new Date();
        defDateStart.setDate(defDateStart.getDate() - 30);
        var defDateEnd = new Date();
        var $dateStart = $('#date-download-start').pickadate('picker');
        $dateStart.set('select', defDateStart);
        var $dateEnd = $('#date-download-end').pickadate('picker');
        $dateEnd.set('select', defDateEnd);
        // 初始化Word输出弹出窗体
        var defDateEndDocx = new Date();
        var week = defDateEndDocx.getDay();
        if (week < 5)       // 星期日至星期四
            defDateEndDocx.setDate(defDateEndDocx.getDate() - week - 2);
        else if (week > 5)  // 星期六
            defDateEndDocx.setDate(defDateEndDocx.getDate() - 1);
        var defDateStartDocx = new Date();
        defDateStartDocx.setDate(defDateEndDocx.getDate() - 4);

        var $dateStartDocx = $('#date-docx-start').pickadate('picker');
        $dateStartDocx.set('select', defDateStartDocx);
        var $dateEndDocx = $('#date-docx-end').pickadate('picker');
        $dateEndDocx.set('select', defDateEndDocx);
    }

    // 初始化日志表
    function intiRecordPage() {
        // 刷新日志表
        FreshRecordTable();
    }

    // 初始化每周计划页面
    function intiWeekPlan() {
        $('.week-plan-line').prop("onclick", null).off("click");
        var rootNode = document.getElementById("week-plan-root");
        rootNode.innerHTML = '';        // 首先清空现有html

        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/Pages/DbService.asmx/GetWeekPlans",
            data: "{'userName':'" + userName + "', ascSort:'false'}",
            dataType: 'json',
            async: false,
            timeout: 3000,
            error: function (x, e) {
                if (_debug) console.log(e);
            },
            success: function (result) {
                if (result == null || result.d === '') return;
                var res = eval('(' + result.d + ')');
                var resLength = res.length;

                var indexAdded = 0;
                var htmlAdd = '<div class="ui horizontal segments">';
                for (var i = 0; i < resLength; i ++) {
                    if (i == 0 || (res[i].PlanList != null && res[i].PlanList !== '')) {
                        htmlAdd += getStrHtmlWeekPlanList(res[i].Date, res[i].PlanList);
                        indexAdded++;
                        if (indexAdded == 3) {
                            htmlAdd += '</div>';
                            htmlAdd += '<div class="ui horizontal segments">';
                            indexAdded = 0;
                        }
                    }
                }

                if (!htmlAdd.endsWith('</div>')) htmlAdd += '</div>';
                rootNode.innerHTML = htmlAdd;
            }
        });
    }

    // 初始化待办事项页面
    function intiTodoPage() {
        // 初始化控件状态
        var $cbShowFinished = $('#cb-todo-show-finished');
        $cbShowFinished.css("margin-top", "0.678571em");    //布局调整为与右侧相同
        $cbShowFinished.checkbox('check');
        // 读取todo列表
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            url: "/Pages/DbService.asmx/GetAllTodos",
            data: "{userName:'" + userName + "'}",
            dataType: 'json',
            timeout: 10000,
            complete: function(request, status) {
            },
            error: function(x, e) {
                if (_debug) console.log(e);
            },
            success: function(result) {
                if (result.d === '') {
                    if (_debug) console.log('读取TODO列表数据失败！-' + result.d + '-');
                    return;
                }

                var res = eval('(' + result.d + ')');
                $.each(res, function(i, n) {
                    addTodoTable(n.Id, n.Text, n.FinishDate, n.Finished);
                });
                // 改变行数显示
                changeTodoNum();
                // 添加用户输入响应
                addListenerShowFinishedTodos();
            }
        });
    }

    // 初始化心情图表
    function intiModChart() {
        freshModDate();
    }

    // 绑定按钮点击事件
    function intiBtnClick() {
        $('#btn-out-docx').click(function () {
            $('#modal-docx-date').modal('show');
            setTimeout(function () {
                var $dateStart = $('#date-docx-start').pickadate('picker');
                $dateStart.close(true);
            }, 510);
        });

        $('#btn-out-excel').click(function () {
            $('#modal-download-date').modal('show');
            setTimeout(function () {
                var $dateStart = $('#date-download-start').pickadate('picker');
                $dateStart.close(true);
            }, 510);
        });

        $('#btn-export-excel-ok').click(function () {
            // 获取数据
            var $dateStart = $('#date-download-start').pickadate('picker');
            var $dateEnd = $('#date-download-end').pickadate('picker');
            var startDate = $dateStart.get('highlight', 'yyyy-mm-dd');
            var endDate = $dateEnd.get('highlight', 'yyyy-mm-dd');
            $('#modal-loading').modal('show');

            $.ajax({
                type: "POST",
                contentType: "application/json;charset=utf-8",
                url: "/Pages/DbService.asmx/GetExportExcelName",
                data: "{userName:'" + userName + "',startDate:'" + startDate + "',endDate:'" + endDate + "'}",
                dataType: 'json',
                timeout: 10000,
                complete: function (request, status) {
                    // 延缓关闭读取等待框，避免读取速度过快无法关闭
                    var timerTmp = window.setTimeout(function () {
                        $('#modal-loading').modal('hide');
                        if (timerTmp != null) window.clearTimeout(timerTmp);
                    }, 1000);
                },
                error: function (x, e) {
                    if (_debug) console.log(e);
                },
                success: function (result) {
                    if (result.d === "") {
                        if (_debug) console.log('生成Excel下载文件失败！');
                        return;
                    }

                    if (_debug) {
                        console.log('待下载的文件名：');
                        console.log(result.d);
                    }

                    // 下载
                    downloadFile('/UploadFiles/ExcelOutFiles/' + result.d);
                    /*
                    fetch('/UploadFiles/ExcelOutFiles/' + result.d).then(res => res.blob().then(blob => {
                        var a = document.createElement('a');
                        var url = window.URL.createObjectURL(blob);
                        var filename = result.d;
                        a.href = url;
                        a.download = filename;
                        a.click();
                        window.URL.revokeObjectURL(url);
                    }));
                    */
                }
            });
        });

        $('#btn-export-docx-ok').click(function () {
            // 获取数据
            var $dateStart = $('#date-docx-start').pickadate('picker');
            var $dateEnd = $('#date-docx-end').pickadate('picker');
            var startDate = $dateStart.get('highlight', 'yyyy-mm-dd');
            var endDate = $dateEnd.get('highlight', 'yyyy-mm-dd');
            $('#modal-loading').modal('show');

            $.ajax({
                type: "POST",
                contentType: "application/json;charset=utf-8",
                url: "/Pages/DbService.asmx/GetExportDocxName",
                data: "{userName:'" + userName + "',startDate:'" + startDate + "',endDate:'" + endDate + "'}",
                dataType: 'json',
                timeout: 10000,
                complete: function (request, status) {
                    // 延缓关闭读取等待框，避免读取速度过快无法关闭
                    var timerTmp = window.setTimeout(function () {
                        $('#modal-loading').modal('hide');
                        if (timerTmp != null) window.clearTimeout(timerTmp);
                    }, 1000);
                },
                error: function (x, e) {
                    if (_debug) console.log(e);
                },
                success: function (result) {
                    if (result.d === "") {
                        if (_debug) console.log('生成Word下载文件失败！');
                        return;
                    }

                    if (_debug) {
                        console.log('待下载的文件名：');
                        console.log(result.d);
                    }

                    // 下载
                    downloadFile('/UploadFiles/DocxOutFiles/' + result.d);
                    /*
                    fetch('/UploadFiles/DocxOutFiles/' + result.d).then(res => res.blob().then(blob => {
                        var a = document.createElement('a');
                        var url = window.URL.createObjectURL(blob);
                        var filename = result.d;
                        a.href = url;
                        a.download = filename;
                        a.click();
                        window.URL.revokeObjectURL(url);
                    }));
                    */
                }
            });
        });

        $('#btn-exit').click(function () {
            storage.removeItem('userName');
            location.href = "/";
        });

        // 待办事项页面中添加页面按钮事件
        $('#btn-add-todo').click(function() {
            var msg = $('#tb-todo-msg').val();
            var finishDate = $('#date-todo-finish').val();

            if (msg == null || msg === "" || msg.trim() === "") {
                showAlert('请填入待加入的待办项信息。');
                return;
            }
            if (finishDate == null || finishDate === "" || finishDate.trim() === "") {
                showAlert('请填入待加入的待办项完成日期。');
                return;
            }

            $('#btn-add-todo').addClass('loading');
            // 向数据库加入todo项
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=utf-8",
                url: "/Pages/DbService.asmx/AddTodo",
                data: "{userName:'" + userName + "',text:'" + msg + "',finishDate:'" + finishDate + "'}",
                dataType: 'json',
                timeout: 5000,
                complete: function(request, status) {
                    $('#btn-add-todo').removeClass('loading');
                },
                error: function(x, e) {
                    if (_debug) console.log(e);
                },
                success: function(result) {
                    if (result.d === "-1") {
                        if (_debug) console.log('添加TODO行数据失败！');
                        return;
                    }
                    addTodoTable(result.d, msg, finishDate, false);
                    // 改变行数显示
                    changeTodoNum();
                }
            });
        });

        $('#btn-mod-create').click(function () {
            freshModDate();
        });
    }

    // 初始化html标签
    function intiDiv() {
        $('.ui.checkbox').checkbox('is checked');
        $('#modal-loading').modal('setting', 'closable', false);
        $('.ui.dropdown').dropdown({
            allowAdditions: true
        });

        $('#tb-user-name').text("\r\n" + userName + "\r\n");

        // 添加Tabpage的切换功能
        $('.menu .item').tab();
    }

    // 修改现有待办事项个数
    function changeTodoNum() {
        var num = $('#tbody-todo-table').children('tr').length;
        $('#lbl-todo-num').text(num);
        if (num >= 10) {
            $('#lbl-todo-num').removeClass('blue');
            $('#lbl-todo-num').addClass('red');
        } else {
            $('#lbl-todo-num').removeClass('red');
            $('#lbl-todo-num').addClass('blue');
        }
    }

    // 为待办事项页中显示完成项选项添加响应
    function addListenerShowFinishedTodos() {
        var $cbShowFinished = $('#cb-todo-show-finished');
        $cbShowFinished.checkbox({
                onChange: function() {
                    var $trs = $('#tbody-todo-table > tr');
                    var checked = $cbShowFinished.checkbox('is checked');
                    if (checked) {
                        $($trs).each(function(i, e) {
                            e.style.display = 'table-row';
                        });
                    } else {
                        $($trs).each(function(i, e) {
                            var $chk = $(e).find('.checkbox');
                            var chked = $chk.checkbox('is checked');
                            if (chked) e.style.display = 'none';
                            else e.style.display = 'table-row';
                        });
                    }
                }
            }
        );
    }

    // 为待办事项列表添加一行
    function addTodoTable(id, msg, finishTime, finished) {
        // 添加一行表格
        if (typeof id == 'number') id = id.toString();
        var htmlAdd = '<tr>' +
            '<td class="todo-id">' + id + '</td>' +
            '<td class="collapsing">' +
            '<div class="ui fitted toggle checkbox">' +
            '<input type="checkbox"> <label></label>' +
            '</div>' +
            '</td>' +
            '<td class="todo-msg">' + msg + '</td>' +
            '<td class="todo-finish-time">' + finishTime + '</td>' +
            '<td><button class="ui basic button btn-todo-modify"><i class="write icon"></i>修改</button></td>' +
            '<td><button class="ui basic button btn-todo-del"><i class="minus icon"></i>删除</button></td>' +
            '</tr>';

        $('#tbody-todo-table').append(htmlAdd);
        // 获取变量
        var $tr = $('#tbody-todo-table:last-child');
        var $id = $('.todo-id:last', $tr);
        var $msg = $('.todo-msg:last', $tr);
        var $chkFinished = $('.ui.checkbox:last', $tr);
        var $finishTime = $('.todo-finish-time:last', $tr);
        var $btnModify = $('.btn-todo-modify:last', $tr);
        var $btnDel = $('.btn-todo-del:last', $tr);
        // 行数值调整
        if (finished === true) $chkFinished.checkbox('check');
        if (new Date(finishTime) < new Date())
            $finishTime.addClass('error');
        // 初始化选择框
        $chkFinished.checkbox({
                onChange: function() {
                    // 从数据库修改todo项的完成状态
                    $.ajax({
                        type: "POST",
                        contentType: "application/json;charset=utf-8",
                        url: "/Pages/DbService.asmx/UpdateChecked",
                        data: "{id:'" + $id.text() + "',finished:'" + $chkFinished.checkbox('is checked').toString() + "'}",
                        dataType: 'json',
                        timeout: 5000,
                        complete: function(request, status) {
                        },
                        error: function(x, e) {
                            if (_debug) console.log(e);
                        },
                        success: function(result) {
                            if (result.d !== "Success") {
                                if (_debug) console.log('修改TODO行选择数据失败！');
                                return;
                            }
                        }
                    });
                }
            }
        );

        // 初始化修改按钮
        $btnModify.click(function () {
            $btnModify.addClass('loading');
            // 更新修改对话框的信息
            var isChecked = $chkFinished.checkbox('is checked');
            if (isChecked === true) $('#cb-todo-row-modify').checkbox('check');
            $('#tb-todo-row-modify').val($msg.text());
            var $dateModify = $('#date-todo-row-modify').pickadate('picker');
            $dateModify.set('select', $finishTime.text(), { format: 'yyyy-mm-dd' });
            $('#btn-todo-row-modify-ok').unbind('click');
            $('#btn-todo-row-modify-ok').click(function () {
                // 获取修改项的值
                var isCheckedMod = $('#cb-todo-row-modify').checkbox('is checked');
                var msgMod = $('#tb-todo-row-modify').val();
                var finishTimeMod = $dateModify.get('select', 'yyyy-mm-dd');
                // 校验输入项合法性
                if (msgMod.trim() === "") {
                    showAlert('待办事项不能为空，不能进行修改。');
                    return;
                }
                // 从数据库修改todo项
                $.ajax({
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    url: "/Pages/DbService.asmx/UpdateTodo",
                    data: "{id:'" + $id.text() + "',text:'" + msgMod + "',finishDate:'" + finishTimeMod + "',finished:'" + isCheckedMod.toString() + "'}",
                    dataType: 'json',
                    timeout: 5000,
                    complete: function (request, status) {
                        setTimeout(function () {
                            $btnModify.removeClass('loading');
                        }, 600);
                    },
                    error: function (x, e) {
                        if (_debug) console.log(e);
                    },
                    success: function (result) {
                        if (result.d !== "Success") {
                            if (_debug) console.log('修改TODO行数据失败！');
                            return;
                        }
                        // 修改前台界面显示
                        if (isCheckedMod === true) $chkFinished.checkbox('check');
                        else $chkFinished.checkbox('uncheck');
                        $msg.text(msgMod);
                        $finishTime.text(finishTimeMod);
                        if (new Date(finishTimeMod) < new Date()) $finishTime.addClass('error');
                        else $finishTime.removeClass('error');
                    }
                });

            });
            // 显示修改对话框
            $('#modal-todo-row').modal('show');
        });
        // 初始化删除按钮
        $btnDel.click(function () {
            $btnDel.addClass('loading');
            // 从数据库删除todo项
            $.ajax({
                type: "POST",
                contentType: "application/json;charset=utf-8",
                url: "/Pages/DbService.asmx/DeleteTodo",
                data: "{id:'" + $id.text() + "'}",
                dataType: 'json',
                timeout: 5000,
                complete: function (request, status) {
                    $btnDel.removeClass('loading');
                },
                error: function (x, e) {
                    if (_debug) console.log(e);
                },
                success: function (result) {
                    if (result.d !== "Success") {
                        if (_debug) console.log('添加TODO行数据失败！');
                        return;
                    }
                    // 删除html
                    $btnDel.parent().parent().remove();
                    // 改变行数显示
                    changeTodoNum();
                }
            });
        });
    }

    // 启动时的初始化函数
    $(function () {
        // 字符串功能扩展
        stringExtFunction();
        // 读取基本数据
        storage = window.sessionStorage;
        userName = storage.userName;
        // 页面初始化
        intiDiv();
        intiDropzone();
        intiDate();
        intiRecordPage();
        intiTodoPage();
        intiBtnClick();
        intiWeekPlan();
        intiModChart();
    });
</script>

</body>
</html>
